package com.cooba.news_frament;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.NewsDetailsActivity;
import com.cooba.adapter.NewsAdapter;
import com.cooba.application.MyApplication;
import com.cooba.bean.BannerBean;
import com.cooba.bean.BannerStatistic;
import com.cooba.bean.NewsLoad;
import com.cooba.content_frament.BaseFragment;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.ACache;
import com.cooba.utils.CarURL;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.ServerURL;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2015/12/24.
 * 热点
 */
public class LiteratureFrament extends BaseFragment {

    private View view;
    private PullToRefreshListView rListView;
    private HttpUtils httpUtils;
    private RequestParams params;
    private List<NewsLoad.NewsListEntity> list = new ArrayList<>();
    private NewsAdapter mAdapter;

    private TextView tv_refreshFlag;
    private BannerBean banner;
    private String min_id = "0";
    private String max_id = "0";
    private NewsLoad newsLoad;
    private ACache acache;
    private boolean first_flag = true;
    private int currentpage = 1;
    private Boolean isIncar;
    private String mac;
    private String next_key = "0";
    private boolean mIsFirstLoad=true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try {
            if (view == null) {
                view = initview(inflater);

            }
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.base_frament, null, false);
        initPullTorefresh(view);
        initLoadViewHelper(rListView);
        acache = ACache.get(getContext());
        return view;
    }


    private void initPullTorefresh(View view) {
        tv_refreshFlag = (TextView) view.findViewById(R.id.test);
        rListView = (PullToRefreshListView) view.findViewById(R.id.lv_news);
        if (isIncar) {
            rListView.setPullRefreshEnabled(false);
        } else {
            rListView.setPullRefreshEnabled(true);
        }
        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
                Log.d("wei", first_flag + "---");
                if (first_flag) {
                    getFirstData();
                    //getBanner();
                } else {
                    getRefreshData();
                }
                String stringDate = CommonUtil.getStringDate();
                rListView.setLastUpdatedLabel(stringDate);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getMoreData();
            }
        });

        rListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String replyid;
                if (banner != null && banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                    replyid = mAdapter.getList().get(position - 1).id;
                } else {
                    replyid = mAdapter.getList().get(position).id;
                }
                Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
                intent.putExtra("newsDetialreplyid", replyid);
                intent.putExtra("dirname", "peri");
                startActivity(intent);
                // 放入已读列表
                saveToReadedList(view, replyid);
            }
        });
    }

    private void saveToReadedList(View view, String replyid) {
        acache.put("readed_news_list_" + replyid, "true", SAVE_TIME);//保存一个月
        TextView tvTitle = (TextView) view.findViewById(R.id.tv_tittle);
        if (tvTitle != null) {
            tvTitle.setTextColor(getResources().getColor(R.color.darkgray));
        }
    }

    //获取顶部广告条
    private void getBanner() {
        String urlbanner;
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String now_time = sDateFormat.format(new java.util.Date());
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("now_time", now_time);
        params.addBodyParameter("tag", "literature_new");
        if (isIncar) {
            params.addBodyParameter("mac", mac);
            urlbanner =CarURL.bannerList;
        } else {
            urlbanner = ServerURL.httpUrl + ServerURL.bannerList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlbanner, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
                // getFirstData();
                String cacheData=acache.getAsString("literature_news_banner");
                if (cacheData!=null){
                    banner = new Gson().fromJson(cacheData, BannerBean.class);
                    if (banner.getBannerList()!=null&&banner.getBannerList().size() > 0) {
                        initHeadView();
                    }
                }else {
                    getFirstData();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                try {
                    banner = new Gson().fromJson(responseInfo.result, BannerBean.class);
                    if (banner.getBannerList()!=null&&banner.getBannerList().size() > 0) {
                        initHeadView();
                        acache.put("literature_news_banner",responseInfo.result,SAVE_TIME);
                    } else {
                        getFirstData();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getMoreData() {
        String urlnews;
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "peri");
        params.addBodyParameter("min_id", min_id);
        params.addBodyParameter("page_size", "10");
        if (isIncar) {
            params.addBodyParameter("next_key", next_key);
            urlnews =CarURL.newsList;
        } else {
            urlnews = ServerURL.httpUrl + ServerURL.newsList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlnews, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
                currentpage++;
                String cacheData = acache.getAsString("literature_news_load_more_" + currentpage);//从缓存中取数据
                Log.d("wei--", "加载更多读取:" + acache.getAsString("literature_news_load_more_" + currentpage));
                if (cacheData != null) {
                    newsLoad = new Gson().fromJson(cacheData, NewsLoad.class);
                    if (newsLoad.newsList != null&&newsLoad.newsList.size()>0) {
                        mAdapter.addMoreData(newsLoad.newsList);
                        min_id = newsLoad.newsList.get(newsLoad.newsList.size() - 1).getId();
                        if (newsLoad.newsList.size()<10){
                            rListView.setHasMoreData(false);
                        }
                    }
                } else {
                    currentpage--;
                    Toast.makeText(getContext(),"无网络!",Toast.LENGTH_SHORT).show();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                try {
                    newsLoad = new Gson().fromJson(responseInfo.result, NewsLoad.class);
                    if (newsLoad.newsList != null&&newsLoad.newsList.size()>0) {
                        mAdapter.addMoreData(newsLoad.newsList);
                        min_id = newsLoad.newsList.get(newsLoad.newsList.size() - 1).getId();
                        if (isIncar) {
                            next_key = newsLoad.getNext_key();
                        }
                        currentpage++;
                        acache.put("literature_news_load_more_" + currentpage, responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        if (newsLoad.newsList.size()<10){
                            rListView.setHasMoreData(false);
                        }
                    } else {
                        Toast.makeText(getContext(), "没有更多数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }

    //第一次加载数据
    private void getFirstData() {
        if (mIsFirstLoad){
            helper.showLoading("正在加载...");
        }
        String urlnews;
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "peri");
        params.addBodyParameter("page_size", "10");
        if (isIncar) {
            params.addBodyParameter("next_key", next_key);
            urlnews = CarURL.newsList;
        } else {
            params.addBodyParameter("first_flag", "0");
            urlnews = ServerURL.httpUrl + ServerURL.newsList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlnews, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
                String cacheData = acache.getAsString("literature_news_first");//从缓存中取数据
                Log.d("wei--", "读取:" + acache.getAsString("literature_news_first"));
                if (cacheData != null) {
                    first_flag = false;
                    newsLoad = new Gson().fromJson(cacheData, NewsLoad.class);
                    if (mAdapter == null) {
                        mAdapter = new NewsAdapter(getContext(), newsLoad.newsList);
                        rListView.getRefreshableView().setAdapter(mAdapter);
                    } else {
                        mAdapter.setList(newsLoad.newsList);
                    }
                    max_id = newsLoad.newsList.get(0).getId();
                    min_id = newsLoad.newsList.get(newsLoad.newsList.size() - 1).getId();
                    if (newsLoad.newsList.size()<10){
                        rListView.setHasMoreData(false);
                    }
                }else {
                    Toast.makeText(getContext(),"无网络!",Toast.LENGTH_SHORT).show();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                try {
                    newsLoad = new Gson().fromJson(responseInfo.result, NewsLoad.class);
                    if (newsLoad.newsList!=null&&newsLoad.newsList.size()>0) {
                        if (mAdapter == null) {
                            mAdapter = new NewsAdapter(getContext(), newsLoad.newsList);
                            rListView.getRefreshableView().setAdapter(mAdapter);
                        } else {
                            mAdapter.setList(newsLoad.newsList);
                        }
                        if (isIncar) {
                            next_key = newsLoad.getNext_key();
                        }
                        acache.put("literature_news_first", responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        max_id = newsLoad.newsList.get(0).getId();
                        min_id = newsLoad.newsList.get(newsLoad.newsList.size() - 1).getId();
                        first_flag = false;
                        if (newsLoad.newsList.size()<10){
                            rListView.setHasMoreData(false);
                        }
                        mIsFirstLoad = false;
                        helper.restore();
                    }else {
                        helper.showEmpty("暂时没有数据", "重新加载",true, new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                helper.restore();
                                getFirstData();
                            }
                        });
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }

    //刷新数据
    private void getRefreshData() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "peri");
        params.addBodyParameter("max_id", max_id);
        params.addBodyParameter("limit_num", "10");
        //String url="http://a.cooba.cc/Port/newsPortInfoList";

        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.newsList, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
                String cacheData = acache.getAsString("literature_news_refresh_" + max_id);//从缓存中取数据
                if (cacheData != null) {
                    newsLoad = new Gson().fromJson(cacheData, NewsLoad.class);
                    if (newsLoad.newsList != null&&newsLoad.newsList.size()>0) {
                        mAdapter.addNewData(newsLoad.newsList);
                        max_id = newsLoad.newsList.get(0).getId();
                        if (newsLoad.newsList.size()<10){
                            rListView.setHasMoreData(false);
                        }
                    }
                }else {
                    Toast.makeText(getContext(),"无网络!",Toast.LENGTH_SHORT).show();
                }

                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                try {
                    newsLoad = new Gson().fromJson(responseInfo.result, NewsLoad.class);
                    if (newsLoad.newsList != null&&newsLoad.newsList.size()>0) {
                        mAdapter.addNewData(newsLoad.newsList);
                        max_id = newsLoad.newsList.get(0).getId();
                        acache.put("literature_news_refresh_" + max_id, responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        if (newsLoad.newsList.size()<10){
                            rListView.setHasMoreData(false);
                        }
                    } else {
                        Toast.makeText(getContext(), "暂时没有新数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }


    private void initHeadView() {
        //rListView.getRefreshableView().setAdapter(null);
        rListView.getRefreshableView().addHeaderView(getCustomHeaderView(getContext(), banner.getBannerList()));
        getFirstData();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
            Log.d("wei--", "Literature:" + isVisibleToUser);
        initIncar();
        if (getUserVisibleHint()) {
            if (banner == null)
                getBanner();
        }
    }

    public void initIncar() {
        MyApplication application = MyApplication.getMyApplication();
        isIncar = application.getIsInCar();
        mac = application.getMac();
    }
}